import { useRef, useState } from "react"

const useTableSelector = <T>() => {
  const values = useRef<Map<number, T[]>>(new Map())
  const [effect, setEffect] = useState(0)

  const getSelected = (pageNum?: number) => {
    if (pageNum) {
      return values.current.get(pageNum) || []
    } else {
      const result: T[] = []
      values.current.forEach((value) => {
        result.push(...value)
      })
      return result
    }
  }

  const setSelected = (pageNum: number, rows: T[]) => {
    values.current.set(pageNum, rows)
    setEffect(effect + 1)
  }

  const clearSelected = () => {
    values.current.clear()
    setEffect(effect + 1)
  }

  return {
    getSelected,
    setSelected,
    effect,
    clearSelected,
  }
}

export default useTableSelector
